import asyncio
import aiohttp
import json


async def test_stepFunApi():
    """
    测试 stepFunApi 接口
    使用 aiohttp 发送 POST 请求
    """
    # API 端点（根据实际部署情况修改）
    url = "http://localhost:8016/v1/chat/completions"
    # url = "http://localhost:18002/v1/chat/completions"

    # 构建请求体，模拟 OpenAI Chat Completions API 格式
    request_body = {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "请识别这张图片中的文字"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            # 替换为实际的图片URL
                            # "url": "https://hf-mirror.com/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg",
                            "url": "https://cdn-img.gitcode.com/dc/db/09355119d1c8db4814dfded3ebf1b5f2fb856e8a1c5561878942099125f163cf.png?userid=123123"
                        }
                    }
                ]
            }
        ]
    }

    async with aiohttp.ClientSession() as session:
        try:
            print(f"发送 POST 请求到: {url}")
            print(f"请求体: {json.dumps(request_body, indent=2, ensure_ascii=False)}")

            async with session.post(
                    url,
                    json=request_body,
                    headers={"Content-Type": "application/json"}
            ) as response:
                # 获取响应状态码
                status = response.status
                print(f"\n响应状态码: {status}")

                # 获取响应头
                print(f"响应头: {dict(response.headers)}")

                # 获取响应内容
                response_data = await response.json()
                print(f"\n响应内容:")
                print(json.dumps(response_data, indent=2, ensure_ascii=False))

                # 验证响应
                if status == 200:
                    print("\n✅ 请求成功")
                    if response_data.get("success") is not False:
                        print("✅ API 返回成功状态")
                    if "choices" in response_data:
                        print("✅ 响应包含 choices 字段")
                        if len(response_data["choices"]) > 0:
                            content = response_data["choices"][0].get("message", {}).get("content", "")
                            print(f"✅ OCR 结果: {content[:100]}..." if len(content) > 100 else f"✅ OCR 结果: {content}")
                else:
                    print(f"\n❌ 请求失败，状态码: {status}")

        except aiohttp.ClientError as e:
            print(f"\n❌ 网络错误: {e}")
        except json.JSONDecodeError as e:
            print(f"\n❌ JSON 解析错误: {e}")
            text = await response.text()
            print(f"响应文本: {text}")
        except Exception as e:
            print(f"\n❌ 发生错误: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    print("=" * 60)
    print("开始测试 stepFunApi")
    print("=" * 60)

    # 运行基本测试
    asyncio.run(test_stepFunApi())


